package com.xqboss.apps.controller.marketing;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xqboss.apps.domain.consumer.ConsumerAirdropRecord;
import com.xqboss.apps.dto.marketing.AppGetAirdropListDto;
import com.xqboss.apps.enums.marketing.AirdropStatusEnum;
import com.xqboss.apps.enums.nft.NftDispatchSourceEnum;
import com.xqboss.apps.enums.nft.NftTypeEnum;
import com.xqboss.apps.service.consumer.ConsumerAirdropRecordService;
import com.xqboss.apps.service.marketing.AirdropRecordService;
import com.xqboss.apps.service.order.NftDispatchRecordService;
import com.xqboss.apps.util.mh.BeanCopierUtil;
import com.xqboss.apps.vo.marketing.AppAirdropRecord2Vo;
import com.xqboss.apps.vo.marketing.AppAirdropRecordDetail2Vo;
import com.xqboss.apps.vo.marketing.AppAirdropRecordVo;
import com.xqboss.apps.vo.user.UserNFTItemVo;
import com.xqboss.common.annotation.ApiVersion;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Trent
 * @date 2023/9/5
 */
@Api(tags = "营销-空投管理")
@RestController
@RequestMapping("/apps/airdrop")
public class AirdropController extends BaseController {

    @Autowired
    private AirdropRecordService airdropRecordService;
    @Autowired
    private ConsumerAirdropRecordService consumerAirdropRecordService;
    @Autowired
    private NftDispatchRecordService nftRecordService;


    @ApiOperation("获取我的空投列表")
    @GetMapping("list")
    public R<List<AppAirdropRecordVo>> list(@Validated AppGetAirdropListDto params) {
        if (StringUtils.isEmpty(params.getOrderByColumn())) {
            params.setOrderByColumn("id");
            params.setSortAsc(false);
        }
        Long userId = getUserId();
        params.setUserId(userId);
        params.startPageAndOrder();
        List<AppAirdropRecordVo> recordList = airdropRecordService.getUserRecord(params);
        //点击一次自动已读所有消息
        if (CollUtil.isNotEmpty(recordList)) {
            List<Long> sysIds = recordList.stream().map(AppAirdropRecordVo::getId).collect(Collectors.toList());

            List<ConsumerAirdropRecord> consumerList = consumerAirdropRecordService.list(new LambdaQueryWrapper<ConsumerAirdropRecord>()
                    .select(ConsumerAirdropRecord::getAirdropId)
                    .eq(ConsumerAirdropRecord::getUserId, userId)
                    .in(ConsumerAirdropRecord::getAirdropId, sysIds));
            if (CollUtil.isNotEmpty(consumerList)) {
                List<Long> conList = consumerList.stream().map(ConsumerAirdropRecord::getAirdropId).collect(Collectors.toList());
                sysIds.removeIf(conList::contains);
            }

            if (CollUtil.isNotEmpty(sysIds)) {
                ArrayList<ConsumerAirdropRecord> res = new ArrayList<>();
                sysIds.forEach(item -> {
                    ConsumerAirdropRecord record = new ConsumerAirdropRecord();
                    record.setAirdropId(item);
                    record.setUserId(userId);
                    res.add(record);
                });
                consumerAirdropRecordService.saveBatch(res);
            }
        }
        return R.ok(recordList);
    }

    @ApiOperation(value = "获取我的空投列表v2", notes = "v1.1.0")
    @GetMapping("list")
    @ApiVersion(2)
    public R<List<AppAirdropRecord2Vo>> listV2(@Validated AppGetAirdropListDto params) {
        if (StringUtils.isEmpty(params.getOrderByColumn())) {
            params.setOrderByColumn("id");
            params.setSortAsc(false);
        }
        Long userId = getUserId();
        params.setUserId(userId);
        params.startPageAndOrder();
        List<AppAirdropRecord2Vo> recordList = airdropRecordService.listV2(params);
        //点击一次自动已读所有消息
        if (CollUtil.isNotEmpty(recordList)) {
            List<Long> sysIds = recordList.stream().map(AppAirdropRecord2Vo::getId).collect(Collectors.toList());

            List<ConsumerAirdropRecord> consumerList = consumerAirdropRecordService.list(new LambdaQueryWrapper<ConsumerAirdropRecord>()
                    .select(ConsumerAirdropRecord::getAirdropId)
                    .eq(ConsumerAirdropRecord::getUserId, userId)
                    .in(ConsumerAirdropRecord::getAirdropId, sysIds));
            if (CollUtil.isNotEmpty(consumerList)) {
                List<Long> conList = consumerList.stream().map(ConsumerAirdropRecord::getAirdropId).collect(Collectors.toList());
                sysIds.removeIf(conList::contains);
            }

            if (CollUtil.isNotEmpty(sysIds)) {
                ArrayList<ConsumerAirdropRecord> res = new ArrayList<>();
                sysIds.forEach(item -> {
                    ConsumerAirdropRecord record = new ConsumerAirdropRecord();
                    record.setAirdropId(item);
                    record.setUserId(userId);
                    res.add(record);
                });
                consumerAirdropRecordService.saveBatch(res);
            }
        }
        return R.ok(recordList);
    }

    @ApiOperation("获取单个空投详情")
    @GetMapping("detail/{airdropRecordId}")
    public R<AppAirdropRecordVo> detail(@Validated @PathVariable("airdropRecordId")
                                        @ApiParam(value = "空投ID", required = true)
                                        @NotNull(message = "空投ID不能为空")
                                        Long airdropRecordId) {
        AppAirdropRecordVo vo = airdropRecordService.getUserRecord(getUserId(), airdropRecordId);
        return R.ok(vo);
    }


    @ApiVersion(2)
    @ApiOperation("获取单个空投详情")
    @GetMapping("detail/{airdropRecordId}")
    public R<AppAirdropRecordDetail2Vo> detailV2(@Validated @PathVariable("airdropRecordId")
                                        @ApiParam(value = "空投ID", required = true)
                                        @NotNull(message = "空投ID不能为空")
                                        Long airdropRecordId) {
        AppAirdropRecord2Vo vo = airdropRecordService.getUserRecordV2(getUserId(), airdropRecordId);
        AppAirdropRecordDetail2Vo detail = BeanCopierUtil.copy(vo, AppAirdropRecordDetail2Vo.class);
        detail.setNftList(Collections.emptyList());
        // 如果是已发放，并且是装备或者典藏，则获取典藏发放列表
        if(detail.getAirdropStatus() == AirdropStatusEnum.COMPLETE){
            if(detail.getAirdropType() == NftTypeEnum.NORMAL || detail.getAirdropType() == NftTypeEnum.EQUIPMENT){
                List<UserNFTItemVo> nftItemList = nftRecordService.getRecordByOrderItemId(NftDispatchSourceEnum.AIRDROP, detail.getId());
                detail.setNftList(nftItemList);
            }
        }
        return R.ok(detail);
    }

}
